<?php
class Twitter {
    private $credentials, $requestData;
    private $error = false, $response, $requestDone = false;
    private $lastHttpCall;
    public $endpoint = 'http://twitter.com/'; // This shouldn't really be changed, but it's handy for testing purposes

    function __construct($username, $pass) {
        $this->credentials = array(
            "username" => $username,
            "password" => $pass
        );
    }

    // API Methods
    function test() {
        return $this->apiCall("get", "help/test");
    }

    function statusesUserTimeline($page = 0) {
        return $this->apiCall("get", "statuses/user_timeline", array(
            "count" => "200",
            "page"  => $page
        ));
    }
    
    function statusesMentions($page = 0) {
        return $this->apiCall("get", "statuses/mentions", array(
            "count" => "200",
            "page"  => $page
        ));
    }

    function usersShow() {
        return $this->apiCall("get", "users/show", array(
            "id" => $this->credentials['username']
        ));
    }

    function apiCall($httpMethod, $method, $data = false) {
        $this->requestData = $data;
        $this->lastHttpCall = $this->endpoint . "$method.json";
        $r = new HttpRequest($httpMethod, $this->lastHttpCall, $data, $this->credentials);

        $this->requestDone = true;

        if ($r->hasError()) {
            $this->error = $r->getError() . print_r($r->getRequestInfo(), true);
            return false;
        } else {
            $this->response = json_decode($r->getResponse(), true);
            return $this->response;
        }
    }

    // Utility functions
    function toString() {
        if (!$this->requestDone) return false;

        // Pretty-print the last Twitter query with result or error
        $o = "<h1>Error</h1>" .
             "<h2>" . $this->getLastHttpCall() . "</h2>" .
             "<h3>Data:</h3>" .
             $this->print_r($this->requestData) .
             "<hr />";

        if($this->error) {
            $o .= $this->print_r($this->getError());
        } else {
            $data = $this->getResponse();
            $json = json_decode($data, true);
            $o .= $this->print_r($json);
        }

        return $o;
    }

    function print_r($data) {
        return '<pre>' . print_r($data, true) . '</pre>';
    }

    // Getters and setters
    function getError()        { return $this->error; }
    function getResponse()     { return $this->response; }
    function getLastHttpCall() { return $this->lastHttpCall; }
}
?>